import {DvTheme, getDuration} from "./Enums";

const DvThemeModule = {
    namespaced: true,
    state: {
        globalTheme: DvTheme.Themes.PRIMARY,
        globalActiveStatus: DvTheme.Active.ACTIVE,
        _timer: undefined
    },
    mutations: {
        [DvTheme.Mutations.SET_MAIN_THEME]: (state, payload) => state.globalTheme = payload,
        [DvTheme.Mutations.SET_ACTIVE_STATUS]: (state, payload) => state.globalActiveStatus = payload,
        setTimer: (state, payload) => state._timer = payload
    },
    actions: {
        [DvTheme.Actions.PRIMARY]: ({commit}) => commit(DvTheme.Mutations.SET_MAIN_THEME, DvTheme.Themes.PRIMARY),
        [DvTheme.Actions.INFO]: ({commit}) => commit(DvTheme.Mutations.SET_MAIN_THEME, DvTheme.Themes.INFO),
        [DvTheme.Actions.SUCCESS]: ({commit}) => commit(DvTheme.Mutations.SET_MAIN_THEME, DvTheme.Themes.SUCCESS),
        [DvTheme.Actions.WARNING]: ({commit}) => commit(DvTheme.Mutations.SET_MAIN_THEME, DvTheme.Themes.WARNING),
        [DvTheme.Actions.DANGER]: ({commit}) => commit(DvTheme.Mutations.SET_MAIN_THEME, DvTheme.Themes.DANGER),
        [DvTheme.Actions.DARK]: ({commit}) => commit(DvTheme.Mutations.SET_MAIN_THEME, DvTheme.Themes.DARK),
        [DvTheme.Actions.METAL]: ({commit}) => commit(DvTheme.Mutations.SET_MAIN_THEME, DvTheme.Themes.METAL),

        [DvTheme.Actions.ACTIVE]: ({state, commit}) => {
            if (state._timer !== undefined) {
                clearInterval(state._timer)
                commit("setTimer", undefined)
            }
            commit(DvTheme.Mutations.SET_ACTIVE_STATUS, DvTheme.Active.ACTIVE_ING)
            setTimeout(() => {
                commit(DvTheme.Mutations.SET_ACTIVE_STATUS, DvTheme.Active.ACTIVE)
            }, getDuration())
        },
        [DvTheme.Actions.IDLE]: ({state, commit}) => {
            if (state.globalActiveStatus !== DvTheme.Active.ACTIVE) {
                console.warn("layout error", `can not change active status from ${state.globalActiveStatus} to idle but active`)
                return
            }
            commit(DvTheme.Mutations.SET_ACTIVE_STATUS, DvTheme.Active.IDLE_ING)
            let timer = setTimeout(() => {
                commit(DvTheme.Mutations.SET_ACTIVE_STATUS, DvTheme.Active.IDLE)
            }, getDuration() * 20)
            commit("setTimer", timer)
        }
    },
    getters: {
        globalThemeClass: (state) => state.globalTheme,
        globalActiveClass: (state) => state.globalActiveStatus
    }
}
export default DvThemeModule
